<?php
class Soul_Util_Image{
	
	public static function getSize($path){
		return getimagesize($path);
	}

	public static function generateThumbnail($srcFile, $toW = NULL, $toH = NULL, $toFile = NULL, $autoFit = FALSE){
		if(!file_exists($srcFile)){
			return '';
		}
		
		if(is_null($toFile)){
			$srcPath = pathinfo($srcFile);
			$toFile = $srcPath['dirname'].DS.$srcPath['filename']."_$toW_$toH_".$srcPath['extension'];
		}

		$info = "";
		$data = GetImageSize($srcFile,$info);
		switch ($data[2]){
			case 1:
				if(!function_exists("imagecreatefromgif")){
					echo "你的GD库不能使用GIF格式的图片，请使用Jpeg或PNG格式！<a href='javascript:go(-1);'>返回</a>";
					exit();
				}
				$im = ImageCreateFromGIF($srcFile);
				break;
			case 2:
				if(!function_exists("imagecreatefromjpeg")){
					echo "你的GD库不能使用jpeg格式的图片，请使用其它格式的图片！<a href='javascript:go(-1);'>返回</a>";
					exit();
				}
				$im = ImageCreateFromJpeg($srcFile);
				break;
			case 3:
				$im = ImageCreateFromPNG($srcFile);
				break;
		}
		$srcW=ImageSX($im);
		$srcH=ImageSY($im);

		if(!is_null($toW) && !is_null($toH)){
			if($autoFit){
				$srcWH=$srcW/$srcH;
				$toWH=$toW/$toH;
				if($toWH<=$srcWH){
					$ftoW=$toW;
					$ftoH=$ftoW*($srcH/$srcW);
				}else{
					$ftoH=$toH;
					$ftoW=$ftoH*($srcW/$srcH);
				}				
			}else{
				$ftoW=$toW;
				$ftoH=$toH;
			}
		}else{
			if(!is_null($toW)){
				$ftoW = $toW;
				$ftoH = $srcH * ($toW / $srcW);
			}elseif(is_null($toH)){
				$ftoH = $toH;
				$ftoW = $srcW * ($toH / $srcH);
			}
		}
		
		if($srcW>$toW||$srcH>$toH){
			if(function_exists("imagecreatetruecolor")){
				@$ni = ImageCreateTrueColor($ftoW,$ftoH);
				if($ni){
					ImageCopyResampled($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
				}else{
					$ni=ImageCreate($ftoW,$ftoH);
					ImageCopyResized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
				}
			}else{
				$ni=ImageCreate($ftoW,$ftoH);
				ImageCopyResized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
			}
			if(function_exists('imagegif')){
				imagegif($ni,$toFile);
			}elseif(function_exists('imagejpeg')){
				imagejpeg($ni,$toFile);
			}else{
				imagepng($ni,$toFile);
			}
			ImageDestroy($ni);
		}
		ImageDestroy($im);
	}
}